package com.wxx.shares;

import com.wxx.util.SeleniumDownloader;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.Task;

import java.util.List;

public class SharesDownloader extends SeleniumDownloader {
    // 成功插入的行数
    int successCount = 0;

    @Override
    public Page download(Request request, Task task) {
        webDriver.get(request.getUrl());
        if (request.getUrl().equals("http://data.eastmoney.com/zjlx/detail.html")) {
            // 获取总共有多少页
            String strLastPage = webDriver.findElementById("PageCont").findElement(By.xpath("//a[@title='转到最后一页']")).getText();
            int lastPage = Integer.parseInt(strLastPage);

            new Actions(webDriver).moveToElement(webDriver.findElement(By.linkText("下一页"))).perform();

            for (int i = 1; i <= lastPage; i++) {
                parseData(webDriver.findElementById("dt_1"));

                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // 模拟点击下一页
                WebElement nextPageElement = webDriver.findElement(By.linkText("下一页"));
                Actions action = new Actions(webDriver);
                action.moveToElement(nextPageElement).click(nextPageElement).perform();
            }
        }
        return null;
    }

    /**
     * 解析当前页的数据并入库
     *
     * @param tableElement table元素
     */
    private void parseData(final WebElement tableElement) {
        List<WebElement> trElementList = tableElement.findElement(By.tagName("tbody")).findElements(By.tagName("tr"));
        for (WebElement trElement : trElementList) {
            List<WebElement> tdElementList = trElement.findElements(By.tagName("td"));
            String index = tdElementList.get(0).getText();
            String code = tdElementList.get(1).getText();
            String name = tdElementList.get(2).getText();
            String url = tdElementList.get(1).findElement(By.tagName("a")).getAttribute("href");

            SharesEntity entity = new SharesEntity();
            entity.url = url;
            entity.name = name;
            entity.code = code;
            SharesDbManager.getSharesMapper().insert(entity);
            successCount++;
            System.out.println("插入的数据：" + index + "  " + name + "  " + code + "   " + url);
        }
    }
}
